package com.xiaodou.mjf.web.console.investcrowd.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.xiaodou.mjf.application.basic.utils.OperatorUtils;
import com.xiaodou.mjf.application.basic.utils.SequenceGenerator;
import com.xiaodou.mjf.application.core.service.InvestCrowdAuditLogService;
import com.xiaodou.mjf.application.core.service.InvestCrowdControlService;
import com.xiaodou.mjf.application.core.service.InvestCrowdLimitService;
import com.xiaodou.mjf.entity.basic.Operator;
import com.xiaodou.mjf.entity.core.InvestCrowdAuditLog;
import com.xiaodou.mjf.entity.core.InvestCrowdControl;
import com.xiaodou.mjf.entity.core.InvestCrowdLimit;
import com.xiaodou.mjf.infrastructure.common.controller.ApplicationController;
import com.xiaodou.mjf.infrastructure.common.utils.DateUtils;
import com.xiaodou.mjf.infrastructure.common.utils.FileUtils;
import com.xiaodou.mjf.infrastructure.common.utils.Global;

/**
 * 众筹level控制器
 * 
 * @author SMART
 *
 */
@Controller
@RequestMapping("investcrowd/limit")
public class InvestCrowdController extends ApplicationController {
	@Resource
	InvestCrowdLimitService investCrowdLimitService;
	@Resource
	InvestCrowdAuditLogService investCrowdAuditLogService;
	@Resource
	InvestCrowdControlService investCrowdControlService;

	@RequestMapping("")
	public String list(InvestCrowdLimit investCrowdLimit, Model model) {

		return "investcrowd/limit/list";
	}

	/**
	 * 众筹列表
	 * 
	 * @param member
	 * @return
	 */
	@RequestMapping(value = { "data.json" })
	@ResponseBody
	public Map<String, Object> data(InvestCrowdLimit investCrowdLimit) {
		Page<InvestCrowdLimit> page = investCrowdLimitService.page(investCrowdLimit);
		return page(page);
	}

	@RequestMapping(value = { "level", "level/{id}" }, method = RequestMethod.GET)
	public String controlList(@PathVariable String id, InvestCrowdControl investCrowdControl, Model model) {
		model.addAttribute("id", id);
		InvestCrowdLimit investCrowdLimit = investCrowdLimitService.get(id);
		model.addAttribute("status",investCrowdLimit.getStatus());
		return "investcrowd/limit/controllist";
	}

	/**
	 * 众筹level列表
	 * 
	 * @param member
	 * @return
	 */
	@RequestMapping(value = { "controlData.json", "controlData.json/{id}" })
	@ResponseBody
	public Map<String, Object> controlData(@PathVariable String id, InvestCrowdControl investCrowdControl) {
		investCrowdControl.setLimitId(id);
		Page<InvestCrowdControl> page = investCrowdControlService.controlpage(investCrowdControl);
		return page(page);
	}

	@RequestMapping(value = { "add" }, method = RequestMethod.GET)
	public String add(Model model) {
		InvestCrowdLimit investCrowdLimit = new InvestCrowdLimit();
		investCrowdLimit.setMerchantId("MFL_CROWD_20210001");
		investCrowdLimit.setCrowdNo(SequenceGenerator.generateCrowdNo(SequenceGenerator.TYPE_CROWD));
		model.addAttribute("investCrowdLimit", investCrowdLimit);
		return "investcrowd/limit/add";

	}

	@RequestMapping(value = { "save" }, method = RequestMethod.POST)
	public String save(InvestCrowdLimit investCrowdLimit, MultipartFile file, Model model) throws Exception {
		try {
			String path = FileUtils.getPath(InvestCrowdLimit.IMAGE_PATH);
			if (file.getSize() > 0) {
				String fileName = FileUtils.getFileName(file.getOriginalFilename());
				FileUtils.upload(Global.getFtpHost(), Global.getFtpUser(), Global.getFtpPassword(), Global.getFtpPort(), file.getInputStream(), path, fileName);
				investCrowdLimit.setImage(path + "/" + fileName);
			}
			investCrowdLimit.setStatus(InvestCrowdLimit.WAIT_AUDIT);
			investCrowdLimitService.save(investCrowdLimit);

		} catch (Exception ex) {
			logger.error(ex.toString());
			ex.printStackTrace();
			throw ex;
		}
		return "redirect:";
	}

	@RequestMapping(value = { "modify", "modify/{id}" }, method = RequestMethod.GET)
	public String modify(@PathVariable String id, Model model) {
		InvestCrowdLimit investCrowdLimit = investCrowdLimitService.get(id);
		String imgFtpPath = Global.getImgPath();
		model.addAttribute("imgFtpPath", imgFtpPath);
		model.addAttribute("investCrowdLimit", investCrowdLimit);
		return "investcrowd/limit/modify";

	}

	@RequestMapping(value = { "delete", "delete/{id}" })
	@ResponseBody
	public boolean delete(@PathVariable String id, Model model) throws Exception {
		boolean result = false;
		try {
			// 获取产品信息
			InvestCrowdLimit investCrowdLimit = investCrowdLimitService.get(id);
			investCrowdLimit.setStatus(InvestCrowdLimit.DELETE);
			investCrowdLimitService.save(investCrowdLimit);
			result = true;
		} catch (Exception ex) {
			logger.error(ex.toString());
			throw ex;
		}
		return result;
	}
    
    @RequestMapping(value = { "deleteList", "deleteList/{id}" })
	@ResponseBody
	public boolean deleteList(@PathVariable String id, Model model) throws Exception {
    	boolean result = false;
    	try {
			// 获取产品信息
			InvestCrowdControl investCrowdControl = investCrowdControlService.get(id);
			investCrowdControl.setStatus(InvestCrowdLimit.DELETE);
			Integer levelCountBefore = investCrowdControl.getLevel();
			//删除后置为-1
			Integer levelCount = investCrowdControlService.findMaxLevelByLimitId(investCrowdControl.getLimitId());
			investCrowdControl.setLevel(-1);
			if(levelCount==null) {
				levelCount = 0;
			}
			for (int i = levelCountBefore+1; i < levelCount+1; i++) {
				InvestCrowdControl temp = investCrowdControlService.findByLevelAndLimitId(i,investCrowdControl.getLimitId());
				temp.setLevel(i-1);
				investCrowdControlService.save(temp);
			}
			
			investCrowdControlService.save(investCrowdControl);
			result = true;
		} catch (Exception ex) {
			logger.error(ex.toString());
			throw ex;
		}
		return result;
	}

	/**
	 * 众筹审核列表
	 * 
	 * @param investCrowdLimit
	 * @param model
	 * @return
	 */
	@RequestMapping(value = { "auditList" })
	public String auditList(InvestCrowdLimit investCrowdLimit, Model model) {
		return "investcrowd/limit/audit";
	}

	@RequestMapping(value = { "auditData.json" })
	@ResponseBody
	public Map<String, Object> auditData(InvestCrowdLimit investCrowdLimit) {
		Page<InvestCrowdLimit> page = investCrowdLimitService.auditPage(investCrowdLimit);
		return page(page);
	}

	/**
	 * 众筹审核
	 * 
	 * @param id
	 * @param description
	 * @param operatorId
	 * @param merchantId
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = { "audit", "audit/{merchantId}" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> audit(@PathVariable String merchantId, String description, Integer audtiStatus) throws ParseException {

		InvestCrowdAuditLog auditLog = new InvestCrowdAuditLog();
		try {
			InvestCrowdLimit investCrowdLimit = investCrowdLimitService.get(merchantId);
			if (investCrowdLimit == null) {
				return map(false, "数据不存在");
			}
			List<InvestCrowdControl> investCrowdControl = investCrowdControlService.findByLimitId(merchantId);

			if (investCrowdControl.size() < 1) {
				return map(false, "等级列表不存在");
			}

			investCrowdLimit.setStatus(audtiStatus);
			investCrowdLimitService.save(investCrowdLimit);
			//
			Operator operator = OperatorUtils.getOperator();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = sdf.parse(DateUtils.getDateTime());
			auditLog.setAuditTime(date);
			auditLog.setDescription(description);
			auditLog.setMerchantId(merchantId);
			auditLog.setOperatorId(operator.getId());
			investCrowdAuditLogService.save(auditLog);

		} catch (Exception ex) {
			logger.error(ex.toString());
			throw ex;

		}
		return map(true);

	}

	@RequestMapping(value = { "controlModify", "controlModify/{id}" }, method = RequestMethod.GET)
	public String controlModify(@PathVariable String id, Model model) {
		InvestCrowdControl investCrowdControl = investCrowdControlService.get(id);
		InvestCrowdLimit investCrowdLimit = investCrowdLimitService.get(investCrowdControl.getLimitId());
		int amountControlMethod = investCrowdLimit.getAmountControlMethod();
		model.addAttribute("amountControlMethod", amountControlMethod);
		model.addAttribute("id",investCrowdControl.getLimitId());
		model.addAttribute("investCrowdControl", investCrowdControl);
		return "investcrowd/limit/controlModify";

	}
	/**
	 * 审核等级列表
	 * 
	 * @param id
	 * @param investCrowdControl
	 * @param model
	 * @return
	 */
	@RequestMapping(value = { "list", "auditList/list/{id}" }, method = RequestMethod.GET)
	public String controlList(@PathVariable String id, Model model) {
		model.addAttribute("id", id);
		return "investcrowd/limit/auditControlList";
	}
	
	@RequestMapping(value = { "saveControl" }, method = RequestMethod.POST)
	public String saveControl(InvestCrowdControl investCrowdControl, Model model) throws Exception {
		try {
			
			investCrowdControlService.save(investCrowdControl);

		} catch (Exception ex) {
			logger.error(ex.toString());
			ex.printStackTrace();
			throw ex;
		}
		model.addAttribute("id", investCrowdControl.getLimitId());
		InvestCrowdLimit investCrowdLimit = investCrowdLimitService.get(investCrowdControl.getLimitId());
		model.addAttribute("status",investCrowdLimit.getStatus());
		return "investcrowd/limit/controllist";
	}

	@RequestMapping(value = { "addControl", "addControl/{id}" }, method = RequestMethod.GET)
	public String addControl(@PathVariable String id, Model model) {
		Integer levelCount = investCrowdControlService.findMaxLevelByLimitId(id);
		InvestCrowdLimit investCrowdLimit = investCrowdLimitService.get(id);
		InvestCrowdControl investCrowdControl = new InvestCrowdControl();
		int amountControlMethod = investCrowdLimit.getAmountControlMethod();
		investCrowdControl.setCrowdName(investCrowdLimit.getCrowdName());
		if(levelCount==null) {
			levelCount = 0;
		}
		model.addAttribute("level",levelCount+1);
		model.addAttribute("id",id);
		model.addAttribute("amountControlMethod", amountControlMethod);
		model.addAttribute("investCrowdControl",investCrowdControl);
		return "investcrowd/limit/controlAdd";

	}
}
